import sys
import math

synthetic_phi = sys.argv[1]
fitted_phi = sys.argv[2]
topics = int(sys.argv[3])
option = 0
if len(sys.argv)==5:
    option = int(sys.argv[4])

syn_phi = []
## read synthetic phi
input_f = open(synthetic_phi,'r')
for lines in input_f:
    w = lines.strip().split('\t')
    syn_phi.append([])
    for s in w[1].split(' '):
        word_id = int(s.split(':')[0])
        word_prob = float(s.split(':')[1])
        syn_phi[-1].append(word_prob)
input_f.close()

real_phi = []
for i in range(topics):
    real_phi.append([])

## read approximate phi
input_f = open(fitted_phi,'r')
for lines in input_f:
    w = lines.strip().split('\t')
    for s in w[1].split(' '):
        dim_id = int(s.split(':')[0])
        word_prob = float(s.split(':')[1])
        real_phi[dim_id].append(word_prob)
input_f.close()

## match
already = {}
for i in range(len(syn_phi)):
    buffer = []
    for j in range(len(real_phi)):
        result = 0.0

        for k in range(len(syn_phi[0])):
            result = result + math.pow((math.sqrt(syn_phi[i][k]) - math.sqrt(real_phi[j][k])),2)
        #print i,j,result
        buffer.append((result,j))
    buffer = sorted(buffer)
    if option == 0 :
        if buffer[0][1] in already:
            print i,buffer[0][1],buffer[0][0],'!!!!'
        else:
            print i,buffer[0][1],buffer[0][0]
            already[buffer[0][1]] = 1
    else:
        for j in buffer:
            print i,j[1],j[0]
        print
